import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Card, Modal, Table, Select, message } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { formLayout } from '@/utils/utils'
import moment from 'moment'
import { fetchClassifyList, updateClassifyList, delClassifyList, addClassifyList } from '@/services/marketCenter/YHQ'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'


const AddForm = Form.create({})(props => {
  const { form, getVal } = props
  const { getFieldDecorator } = form

  return (
    <Form.Item label="分类名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      {getFieldDecorator('className', {})
        (<Input onChange={e => getVal(e.target.value)} />)}
    </Form.Item>
  )
})

const EditorForm = Form.create({})(props => {
  const { form, currRecord } = props
  const { getFieldDecorator } = form
  return (<>
    <Form.Item label="分类名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      {getFieldDecorator('className', {initialValue: currRecord.className})
        (<Input />)}
    </Form.Item>
    <Form.Item label={`状态`} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
      {getFieldDecorator('status', {initialValue: currRecord.status==0 ? '禁用' : '启用'})(
        <Select style={{width: '100%'}}>
          <Select.Option key={0} value={0}>禁用</Select.Option>
          <Select.Option key={1} value={1}>启用</Select.Option>
        </Select>,
      )}
    </Form.Item>
  </>)
})

const CouponClassify = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [total, setTotalPage] = useState(0)
  const [classifyList, setClassifyList] = useState([])
  const [isEdit, setIsEdit] = useState(false)
  const [visible, setVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [currRecord, setCurrRecord] = useState({})
  const [param, setParam] = useState({
    pageSize: 10,
    pageNo: 1,
  })
  const [addFormParam, setAddFormParam] = useState({className: ''})
  const [editFormParam, setEditFormParam] = useState({})


  useEffect(() => {
    _fetchClassifyList(param)
  }, [])
  const pagination = {
    total: parseInt(total),
    onChange(page) {
      setPageNo(page)
      _fetchClassifyList({
        ...param,
        pageNo: page,
      })
    }
  }
  const _fetchClassifyList = async (param) => {
    const res = await fetchClassifyList(param)
    if (res.code == 0) {
      setClassifyList(res.data)
      setTotalPage(res.total)
    }
  }
  // updateClassifyList, delClassifyList, addClassifyList
  const _addClassifyList = async (addFormParam) => {
    const res = await addClassifyList(addFormParam)
    if (res.code == 0) {
      message.success("添加分类成功")
    } else {
      message.success("添加分类失败")
    }
  }
  const _updateClassifyList = async (editFormParam) => {
    const res = await updateClassifyList(editFormParam)
    if (res.code == 0) {
      message.success("编辑分类成功")
    } else {
      message.success("编辑分类失败")
    }
  }
  const _delClassifyList = async (r) => {
    const res = await delClassifyList({id: r.id})
    if (res.code == 0) {
      message.success("删除分类成功")
    } else {
      message.success("删除分类失败")
    }
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      _fetchClassifyList({
        ...param,
        ...values,
      })
    })
  }
  // 查询条件
  const getFields = () => {
    return (<>
      <Col span={8}>
        <Form.Item label="分类名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
          {getFieldDecorator('className', {})
            (<Input />)}
        </Form.Item>
      </Col>
    </>)
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      case 1:
        setIsEdit(false)
        setVisible(true)
        break;
      default:
        break;
    }
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (v, r, i) => {
        return (<span>{i+1}</span>)
      }
    },
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '分类名称',
      dataIndex: 'className',
      key: 'className',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v, r, i) => {
        return (<span>{v == 1 ? '启用' : '禁用'}</span>)
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (v, r, i) => {
        return (<>
          <Button onClick={() => editCurrRecord(r)} type="primary">编辑</Button>
          <Button onClick={() => _delClassifyList(r)} type="danger" style={{marginLeft: '10px'}}>删除</Button>
        </>)
      }
    },
  ]

  const editCurrRecord = (r) => {
    setVisible(true)
    setIsEdit(true)
    setCurrRecord(r)
    console.log(r)
  }

  const getVal = (val) => {
    setAddFormParam({className: val})
  }
  const handleOk = (e) => {
    let storeFaceGuest = {}
    if (isEdit) {
      console.log('编辑分类')
      _updateClassifyList(editFormParam)
      setConfirmLoading(true)
    } else {
      console.log('新增分类')
      _addClassifyList(addFormParam)
    }
  }

  const handleCancel = () => {
    setVisible(false)
  }
  return (<PageHeaderWrapper>
    <Card>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
    </Card>
    <Card style={{ marginTop: '15px' }}>
      <RenderButtom click={handleBtn} />
      <Table rowKey={record => record.id} pagination={pagination} size="small" columns={columns} dataSource={classifyList} />
    </Card>
    <Modal
      title={isEdit ? "编辑分类" : "新增分类"}
      visible={visible}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      onCancel={handleCancel}
    >
      {isEdit
        ? <EditorForm currRecord={currRecord} />
        : <AddForm getVal={getVal} />}
    </Modal>
  </PageHeaderWrapper>)
}

export default Form.create()(CouponClassify)
